<template>
    <div class="form">

        <yk-space dir="vertical" size="xl">
            <!-- 标题输入框 -->
            <input type="text" placeholder="请输入" class="form_title" v-model="formData.title" />
            <yk-space algin="center">
                <!-- 选择分类 -->
                <div class="subset" style="position: relative;">
                    <input type="text" placeholder="选择分类" class="form_content" disabled v-model="subsetName"
                        style="width: 80px; line-height: 24px; pointer-events: none;" />
                    <IconDownOutline class="form_content_icon" />
                    <div class="yk-dropdown-title">
                        <!-- <yk-dropdown-item :value="item.id"> 绑定了 item.id ，当选中时， yk-dropdown 组件会将绑定的 value 值（即 item.id ）作为参数触发 selected 事件。 -->
                        <yk-dropdown title="下拉菜单" @selected="subsetSelect">
                            <yk-dropdown-item v-for="item in subsetStore.data" :value="item.id">{{ item.name }}
                            </yk-dropdown-item>
                        </yk-dropdown>
                    </div>
                </div>
                <!-- 插入标签 -->
                <yk-space algin="center">
                    <yk-tag v-for="tag in formData.label" class="tag" closeable shape="round" @close="deleteLabel(tag)">
                        {{ tag }}
                    </yk-tag>
                    <yk-text type="thord" @click="showLabel" style="cursor: pointer;white-space:nowrap ;"
                        v-show="formData.label?.length < 3">
                        插入标签
                    </yk-text>
                </yk-space>
            </yk-space>
            <!-- 简介 -->
            <div :class="{ form_introduce: props.classify == 0 }" style="width: 100%;">
                <yk-text-area v-model="formData.introduce" placeholder="请输入简介" :auto-size="raws"></yk-text-area>
            </div>
            <!-- 图片上传 -->
            <div class="form_cover" v-if="props.classify == 0">
                <yk-upload :upload-url="uploadUrl" :file-list="fileUrl" :limit="1" accept="image/*" desc="封面800x600"
                    @handleSuccess="handleUploadSuccess" @handleDelete="handleDelete"></yk-upload>
            </div>
        </yk-space>

        <!-- 标签子内容 -->
        <yk-modal v-model="visible" title="标签" size="s" :show-footer="false">
            <yk-space dir="vertical" size="l">
                <yk-space>
                    <yk-input v-model="inputValue" placeholder="请输入标签.." style="width: 280px;" @submit="addLabel" />
                    <yk-button type="primary" @click="addLabel" style="width: 80px;">添加</yk-button>
                </yk-space>
                <yk-space algin="center" size="s">
                    <!-- 已选的标签 -->
                    <yk-tag v-for="tag in formData.label" closeable shape="round" @close="deleteLabel(tag)"> {{ tag }}
                    </yk-tag>
                </yk-space>
                <!-- 可选的标签 -->
                <yk-space wrap size="s" style="padding-top: 8px;">
                    <yk-tag v-for="tag in labelArr" shape="round" style="cursor: pointer;"
                        @click="selectedLabel(tag.label_name)">
                        {{ tag.label_name }} </yk-tag>
                </yk-space>
            </yk-space>

        </yk-modal>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, watch } from 'vue'
// import { mklabel } from '../../mock/data' // 导入天气数据
import { useSubset } from "../../hooks/subsetHook"
import { useLabel } from '../../hooks/labelHook';
import { useSubsetStore } from '../../stores/subset';
import { baseUrl, baseImgPath } from '../../utils/env';
import { useCode } from '../../hooks/codeHook';
import { deleteFileByUrlApi } from '../../api/file_api'
import { useUserStore } from '../../stores/user';

const userStore = useUserStore();
const { tackleCode } = useCode();
const subsetStore = useSubsetStore();

const {
    rawLabel, //获取标签
    inputValue,
    confirm,
    label,
} = useLabel() //管理标签选择

const {
    rawSubset, //获取分组
} = useSubset() //管理分组选择

const props = defineProps({
    classify: {
        default: 0,
        type: Number
    },
    artData: {
        default: () => { return {} },
        type: Object
    },
    galData: {
        default: () => { return {} },
        type: Object
    }
})

//监听文章表单传过来的数据
watch(() => props.artData, (newValue) => {
    // 传进来的数据赋值给formData
    formData.value = { ...newValue, label: newValue.label || [] }
    // 分类名称赋值
    subsetName.value = subsetStore.data.find((item: any) => item.id === formData.value.subset_id)?.name || ''
    // 将标签数据转换为数组形式（处理可能的空值和不同类型）
    if (formData.value.label) {
        // 如果已经是数组，直接使用
        if (Array.isArray(formData.value.label)) {
            formData.value.label = formData.value.label;
        } else {
            // 如果是字符串，按逗号分割
            formData.value.label = String(formData.value.label).split(',');
        }
    }
    // 对图片进行处理
    if (formData.value.cover) {
        let photo = {
            name: '', // 文件名
            url: baseImgPath + '/' + formData.value.cover, // 文件路径
        }
        fileUrl.value = [photo]
    }

}, { deep: true })

//监听图库表单传过来的数据和subsetStore.data的变化
watch([() => props.galData, () => subsetStore.data], ([newGalData, newSubsetData]) => {
    // 确保两者都有值
    if (newGalData && newSubsetData && newSubsetData.length > 0) {
        formData.value = { ...newGalData, label: newGalData.label || [] }
        // 分类名称赋值
        subsetName.value = newSubsetData.find((item: any) => item.id === formData.value.subset_id)?.name || ''
        // 将标签数据转换为数组形式
        if (formData.value.label) {
            if (Array.isArray(formData.value.label)) {
                formData.value.label = formData.value.label;
            } else {
                formData.value.label = String(formData.value.label).split(',');
            }
        }
    }
}, { deep: true })


const emit = defineEmits([
    'formData', // 提交表单数据
])

const formData = ref<any>({
    title: '', // 标题
    subset_id: undefined, // 分类ID
    label: [],
    introduce: '', // 简介
    cover: '',// 封面
    classify: props.classify
}) // 表单实例 

// 简介行数
const raws = computed(() => {
    if (props.classify == 1) {
        return {
            minRows: 24,
            maxRows: 30,
        }
    } else {
        return {
            minRows: 4,
            maxRows: 10,
        }
    }
})

//标签
const labelArr = ref<any[]>([])
const rawLabelArr = () => {
    // 提取所有label_name到数组
    labelArr.value = []
    for (let i = 0; i < label.value.length; i++) {
        labelArr.value.push(label.value[i])
    }
} //获取标签

//标签弹窗
const visible = ref<boolean>(false)
const showLabel = () => {
    visible.value = true
    rawLabelArr()
}
// 输入的标签文本
// const inputLabel = ref<string>('')

// 添加标签
const addLabel = async () => {
    await confirm()
    await rawLabelArr()
    if (inputValue.value && formData.value.label?.length < 3) { // 检查标签文本是否为空且标签数量不超过3个
        formData.value.label.push(inputValue.value) // 将输入的标签文本添加到数组中
        inputValue.value = '' // 清空输入框
    }
}

//选择标签
const selectedLabel = (value: any) => {
    if (value && formData.value.label?.length < 3) {
        formData.value.label.push(value)
        labelArr.value = labelArr.value.filter((item: any) => { return item != value })
    }
}
//删除标签
const deleteLabel = (value: any) => {
    labelArr.value.unshift(value)
    formData.value.label = formData.value.label.filter((item: any) => { return item != value })

}

//分类名称
const subsetName = ref('')

//选择分类
const subsetSelect = (value: number) => {
    formData.value.subset_id = value
    subsetName.value = subsetStore.data.find((item: any) => item.id === value)?.name || ''
}


//封面 
const uploadUrl = `${baseUrl}/api/file/upload`;
const fileUrl = ref<{ name: string, url: string }[]>([])

//图片提交成功
const handleUploadSuccess = (res: any) => {
    if (tackleCode(res.code)) {
        let fileData = res.data
        let photo = {
            name: fileData.file_name, // 文件名
            url: baseImgPath + '/' + fileData.url, // 文件路径
        }
        fileUrl.value.push(photo)
        formData.value.cover = fileData.url
    }
}
//图片删除
const handleDelete = (index: number) => {
    try {
        let req = {
            token: userStore.token,
            fileUrl: formData.value.cover
        }
        deleteFileByUrlApi(req).then((res) => {
            if (tackleCode(res.data.code)) {
                console.log('删除成功', res.data)
            }
        })
        fileUrl.value.splice(index, 1)
    } catch {
        console.log('删除失败')
    }
}



watch(() => formData.value, (newValue) => {
    if (!newValue.subset_id) {
        newValue.subset_id = -1;
    }
    emit('formData', { ...newValue, classify: props.classify }) // 提交表单数据
}, { deep: true })

onMounted(() => {
    rawLabel(),
    rawSubset(props.classify)
})

</script>

<style scoped lang="less">
.form {
    position: relative;

    input {
        border: none;
        background: transparent;
        outline: none;

        &::placeholder {
            color: @gray-4;
        }
    }

    &_title {
        font-size: @size-xl ;
        font-weight: 600;
    }

    // 覆盖简介输入框原有的样式

    .yk-dropdown-title {
        position: absolute;
        height: 24px;
        top: 0;
        left: 0;
        width: 100%;
        pointer-events: auto;
        z-index: 10;
    }

    .yk-text-area {
        border: none;
        padding: 0;
        background-color: transparent;
    }

    // &_introduce {
    //     border-bottom: 1px solid @gray-2;
    // }

    &_cover {
        position: absolute;
        top: 0;
        right: 0;

    }

    :deep(.yk-dropdown__title) {
        opacity: 0;
    }

    :deep(.yk-upload__picture-button) {
        width: 160px;
        height: 120px;
    }

    :deep(.yk-upload-picture) {
        width: 160px;
        height: 120px;
    }

    :deep(.yk-upload__picture) {
        width: 160px;
        height: 120px;
    }
}
</style>